﻿

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using Accord.MachineLearning;
using Accord.Imaging;
using Accord.Math;
using Accord.Statistics;
using System.Threading;
using System.Drawing.Drawing2D;
using System.Diagnostics;


namespace KMeansClustering
{
    public partial class MainForm : Form
    {
        Stopwatch stopWatch = new Stopwatch();
        TimeSpan ts;
        int iter,res;
        int k;
        int[] idx;
        double[] resultA;
        double[][] pixels;
        double[,] allIteration=new double[3,3];
        double[,] helpa,helpb, PixelMatrix,NewD,MatA;
        Bitmap imageSelected,firstAlgorithmCluster;
        Bitmap image;
        KMeans kmeans;
        RadioButton getSelection;
        resampling res1;
        int[][] allIterationPartition;
        private secondForm bigChart;
        private thirdForm bigChart2;
        private historyChartForm historyChart;
        int historyImg = 0;
        bool secondTab = true;
       

        public MainForm()
        {
            iter = 0;
            k = 0;
            imageSelected = null;
            InitializeComponent();
        }

        public RadioButton getRadio
        {
            get { return getSelection; }
            set { getSelection = value; }
        }
       
        public int[] GetIdx
        {
            get { return idx; }
            set { idx = value; }
        }

        public double[] GetResultA
        {
            get { return resultA; }
            set { resultA = value; }
        }

        public double[,] PXLMat
        {
            get { return PixelMatrix; }
            set { PixelMatrix = value; }
        }
       
        public double [,] GetAllIteration
        {
            get { return allIteration; }
            set { allIteration = value; }
        }
       
        public double[,] HelpB
        {
            get { return helpb; }
            set { helpb = value; }
        }
      
        public int GetK
        {
            get { return k; }
        }
       
        public int GetImproveRes
        {
            get { return res; }
            set { res = value; }
        }

        public int GetIter
        {
            get { return iter; }
        }

        public Bitmap GetImage
        {
            get { return imageSelected; }
            set { imageSelected = value; }
        }

        public Bitmap GetFirstAlgorithm
        {
            get { return firstAlgorithmCluster; }
            set { firstAlgorithmCluster = value; }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            // Retrieve the number of clusters
            k = (int)numClusters.Value;
            iter = (int)iterationNum.Value;
            if (GetImage == null)
            {
                MessageBox.Show("you must choose image","Important Note",MessageBoxButtons.OK,MessageBoxIcon.Exclamation,
                MessageBoxDefaultButton.Button1);
            }
            // Load original image-----------------------here the user will have to select one picture from the data base
            else
            {
                this.groupBox1.Visible = true;
                this.groupBox2.Visible = true;
                this.groupBox3.Visible = true;
                this.label4.Visible = true;
                this.label3.Visible = true;
                image = GetImage;

               
            // Transform the image into an array of pixel values
             pixels = image.ToDoubleArray();
          
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\inputImage.txt"))
            {
                for (int i = 0; i < pixels.Length; i++)
                {
                    file.Write(i+":");
                    for (int j = 0; j < 3; j++)
                        file.Write(pixels[i][j] + ",");
                    file.WriteLine();
                }
            }

            // Create a K-Means algorithm using given k and a
            //  square euclidean distance as distance metric.
             kmeans = new KMeans(k, Distance.SquareEuclidean);

            // Compute the K-Means algorithm until the difference in
            //  cluster centroids between two iterations is below 0.05
                allIterationPartition=new int [GetIter+1][];  //for chart!!!!!!!
                this.checkedListBox1.SetItemChecked(0, true);
                backgroundWorker1.RunWorkerAsync();

        }//else
        }//button click

        private void button2_Click(object sender, EventArgs e)
        {
            button3.Enabled = false;
            inputTab.SelectedIndex = 0;
            this.getRadio.Checked = false;
            iterationNum.Value = 10;
            numClusters.Value = 5;
            this.pictureBox8.Image = null;
            this.pictureBox9.Image = null;
            this.groupBox1.Visible = false;
            this.label4.Text = "";
            this.chart1.Series.Clear();
            this.chart2.Series.Clear();
            this.checkedListBox2.Enabled = false;
            this.checkedListBox2.SetItemChecked(0, false);
            this.checkedListBox3.Enabled = false;
            this.checkedListBox3.SetItemChecked(0, false);
            this.checkedListBox4.Enabled = false;
            this.checkedListBox4.SetItemChecked(0, false);
            this.checkedListBox5.Enabled = false;
            this.checkedListBox5.SetItemChecked(0, false);
            GetImage = null;
        }//reset
      
        int[] getClustersPartitionSize(int[] a, int size)
        {
            int[] ret = new int[size];
            for (int i = 0; i < a.Length; i++)
                ret[a[i]]++;

            return ret;
        }//getClustersPartitionSize....for the chart

        public int fimdMinArray(double[] arr)
        {
            int min = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[min] > arr[i])
                    min = i;
            }
            return min+2;
        }//fimdMinArray

        private void button3_Click(object sender, EventArgs e)
        {//the resampling phase
            stopWatch.Start(); 
            pixels = image.ToDoubleArray();
            res1 = new resampling(GetIdx.Length, pixels, this.GetIter);
            backgroundWorker5.RunWorkerAsync();         
        } //button3_Click

        private void chart1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.bigChart = new secondForm(allIterationPartition);
            this.bigChart.Show();
        }//chart1_MouseDoubleClick
       
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
            {
                this.getRadio = radioButton1;
                imageSelected = Properties.Resources.duck;
            }
            else if (radioButton2.Checked)
            {
                this.getRadio = radioButton2;
                imageSelected = Properties.Resources.star;
            }
            else if (radioButton3.Checked)
            {
                this.getRadio = radioButton3;
                imageSelected = Properties.Resources.pig;
            }
            else if (radioButton4.Checked)
            {
                this.getRadio = radioButton4;
                imageSelected = Properties.Resources.cat;
            }
            else if (radioButton5.Checked)
            {
                this.getRadio = radioButton5;
                imageSelected = Properties.Resources.car;
            }
            else if (radioButton6.Checked)
            {
                this.getRadio = radioButton6;
                imageSelected = Properties.Resources.colorful;
            }
            else if (radioButton7.Checked)
            {
                this.getRadio = radioButton7;
                imageSelected = Properties.Resources.cup;
            }
            else if (radioButton8.Checked)
            {
                this.getRadio = radioButton8;
                imageSelected = Properties.Resources.green;
            }
        }//radio button
        
        private double[,] ProgressBarMul(double[,] right, double[,] left,int worker)
        {

            if (right.GetLength(1) == left.GetLength(0))
            {
                double[,] c = new double[right.GetLength(0), left.GetLength(1)];
                for (int i = 0; i < c.GetLength(0); i++)
                {
                    if(worker==3)
                    backgroundWorker3.ReportProgress(i * 100 / c.GetLength(0));
                    else
                    backgroundWorker4.ReportProgress(i * 100 / c.GetLength(0));

                    for (int j = 0; j < c.GetLength(1); j++)
                    {
                        c[i, j] = 0;
                        for (int k = 0; k < right.GetLength(1); k++)
                        {
                            if (Double.IsNaN(left[k, j]))
                                left[k, j] = 0.0;
                            c[i, j] = c[i, j] + right[i, k] * left[k, j];
                        }
                    }
                }
                return c;
            }
            else
            {
                Console.WriteLine("\n Number of columns in Matrix1 is not equal to Number of rows in Matrix2.");
                Console.WriteLine("\n Therefore Multiplication of Matrix1 with Matrix2 is not possible");
                return null;
            }
        }//ProgressBarMul

        private double[,] ProgressBarElementwisePower(double[,] x, double y)
        {
            for (int i = 0; i < x.GetLength(0); i++)
            {
                backgroundWorker4.ReportProgress(i * 100 / x.GetLength(0));
                for (int j = 0; j < x.GetLength(1); j++)
                    x[i, j] = System.Math.Pow(x[i, j], y);
            }
            backgroundWorker4.ReportProgress(0);
            return x;
        }//ProgressBarElementwisePower
        
       
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            progressBar1.CreateGraphics().DrawString("m iteration", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
            for (int i = 0; i < GetIter; i++)//do m iteration
            {
                backgroundWorker1.ReportProgress(i * 100 / GetIter);
                this.GetIdx = kmeans.Compute(pixels, 0.05);  //tolerance value
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\cluster.txt"))
                {
                    for (int j = 0; j < this.GetIdx.Length; j++)
                    {
                        file.Write(j + " , ");
                        file.WriteLine(this.GetIdx[j]);
                    }
                }//print to file

                allIterationPartition[i] = new int[k];
                allIterationPartition[i] = getClustersPartitionSize(this.GetIdx, k);

                myKmeans mykmean = new myKmeans(k, idx, pixels, 0.01);
                double[,] a = mykmean.setAinIterationI();
                double[,] b = allIteration.addition(a);
                this.GetAllIteration = b;

            }//m iteration

        }//backgroundWorker1_DoWork
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage; //update progress bar
            progressBar1.CreateGraphics().DrawString("m iteration", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        }//backgroundWorker1_ProgressChanged
        void backgroundWorker1_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.checkedListBox2.SetItemChecked(0, true);
            this.checkedListBox2.Enabled = true;
            progressBar1.Value = 0;
            backgroundWorker2.RunWorkerAsync();
        }//backgroundWorker1_WorkerCompleted
       
        
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            progressBar1.CreateGraphics().DrawString("finding A", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
            if (this.GetAllIteration.Det() == 0.0)
                MatA = Accord.Math.Matrix.Identity(3);
            else MatA = this.GetAllIteration.inverse();
            double lamdaM = GetIter * 0.01;
            MatA = MatA.multiplyMatrixByNumber(lamdaM);// finite matrix A!!!!!!!!!!!
            for (int i = 0; i < 100; i++)
            {
                backgroundWorker2.ReportProgress(i);
                Thread.Sleep(50);
            }
        }//backgroundWorker2_DoWork
        private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage; //update progress bar
            progressBar1.CreateGraphics().DrawString("finding A", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        }//backgroundWorker2_ProgressChanged
        void backgroundWorker2_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.checkedListBox3.SetItemChecked(0, true);
            this.checkedListBox3.Enabled = true;
            progressBar1.Value = 0;
            backgroundWorker3.RunWorkerAsync();
        }//backgroundWorker2_WorkerCompleted


        private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
        {
            progressBar1.CreateGraphics().DrawString("D=X^TAX", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
            //D=X^TAX
            PixelMatrix = pixels.toMatrix();
            helpa = PixelMatrix.Transpose();
            helpb = MatA.MultiplyMatrix(helpa);
            GC.Collect();
            NewD = ProgressBarMul(PixelMatrix, helpb,3);
        }//backgroundWorker3_DoWork
        private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage; //update progress bar
            progressBar1.CreateGraphics().DrawString("D=X^TAX", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        }//backgroundWorker3_ProgressChanged       
        void backgroundWorker3_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.checkedListBox4.SetItemChecked(0, true);
            this.checkedListBox4.Enabled = true;
            progressBar1.Value = 0;
            backgroundWorker4.RunWorkerAsync();
        }//backgroundWorker3_WorkerCompleted


        private void backgroundWorker4_DoWork(object sender, DoWorkEventArgs e)
        {
            progressBar1.CreateGraphics().DrawString("kmeans", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
            double[,] power = ProgressBarElementwisePower(NewD, 0.5);
            GC.Collect();
            double[,] final = ProgressBarMul(helpa, power,4);
            double[][] X = final.Transpose().to2D();
            this.GetIdx = kmeans.Compute(X, 0.05);
        }//backgroundWorker4_DoWork
        private void backgroundWorker4_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage; //update progress bar
            progressBar1.CreateGraphics().DrawString("kmeans", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        }//backgroundWorker4_ProgressChanged       
        void backgroundWorker4_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.checkedListBox5.SetItemChecked(0, true);
            this.checkedListBox5.Enabled = true;
            pixels.ApplyInPlace((x, i) => kmeans.Clusters.Centroids[this.GetIdx[i]]);
           
            Bitmap res = pixels.ToBitmap(image.Width, image.Height);
            stopWatch.Stop();
            // Show resulting image in the picture box
            if (secondTab)
            {
                button3.Enabled = true;
                pictureBox8.Image = GetImage;
                pictureBox9.Image = res;
                this.firstAlgorithmCluster = res;
                allIterationPartition[GetIter] = getClustersPartitionSize(this.GetIdx, this.GetK);

               
                Series series = null;
                for (int i = 0; i < allIterationPartition.Length; i++)
                {
                    if (i != allIterationPartition.Length - 1)
                        series = this.chart1.Series.Add("iteration " + (i + 1));
                    else series = this.chart1.Series.Add("final partition");
                    

                    for (int j = 0; j < allIterationPartition[0].Length; j++)
                        series.Points.AddXY(Convert.ToString(j + 1), allIterationPartition[i][j]);
                }
                
                this.checkedListBox5.SetItemChecked(0, true);

                label4.Text = k.ToString();
                inputTab.SelectedIndex = 1;
                 GC.Collect();
            }//second tab
            else
            {
                ts = stopWatch.Elapsed;
                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
                label11.Text = elapsedTime;
                label10.Text = this.GetImproveRes.ToString();
                label9.Text = this.GetK.ToString();
                
                double[] x = new double[this.GetResultA.Length];
                for (int i = 0; i < this.GetResultA.Length; i++)
                    x[i] = i + 2;

                
                chart2.Series["C*"].Points.DataBindXY(x, this.GetResultA);
                chart2.Series["C*"].Points[this.GetImproveRes-2].Label = this.GetResultA[this.GetImproveRes-2].ToString();
                chart2.Series["C*"].Points[this.GetImproveRes - 2].MarkerBorderColor = System.Drawing.Color.Red;
                inputTab.SelectedIndex = 2;
                pictureBox10.Image = GetImage;
                pictureBox11.Image = res;
                pictureBox12.Image = this.firstAlgorithmCluster;
            }//third tab
            progressBar1.Value = 0;
      
        }//backgroundWorker4_WorkerCompleted

        private void backgroundWorker5_DoWork(object sender, DoWorkEventArgs e)
        {
           double[] y =res1.improoveResult();
           resultA = new double[y.Length - 2];
           for (int i = 0; i < y.Length-2; i++)
               this.GetResultA[i]= y[i] ;
        }//backgroundWorker5_DoWork
        private void backgroundWorker5_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage; //update progress bar
            progressBar1.CreateGraphics().DrawString("resampling", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        }//backgroundWorker5_ProgressChanged
        void backgroundWorker5_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
      
            res = fimdMinArray(this.GetResultA);
            this.GetImproveRes = res;
            secondTab = false;
            GC.Collect();
            kmeans = new KMeans(res, Distance.SquareEuclidean);
            backgroundWorker1.RunWorkerAsync();
        }//backgroundWorker5_WorkerCompleted
       
        private void chart2_MouseDoubleClick(object sender, EventArgs e)
        {

            this.bigChart2 = new thirdForm(this.GetResultA);
               this.bigChart2.Show();
        }

        private void pictureBox13_MouseHover(object sender, EventArgs e)
        {
            ToolTip toolTip1 = new ToolTip();
            toolTip1.ShowAlways = true;
            toolTip1.IsBalloon = true;
            toolTip1.ToolTipTitle = "number of iterations";
            toolTip1.SetToolTip(pictureBox13, "choose the number of times you want to run the" + System.Environment.NewLine + " traditional k-means"); 
        }

        private void pictureBox14_MouseHover(object sender, EventArgs e)
        {
            ToolTip toolTip2 = new ToolTip();
            toolTip2.ShowAlways = true;
            toolTip2.IsBalloon = true;
            toolTip2.ToolTipTitle = "number of clusters";
            toolTip2.SetToolTip(pictureBox14, "choose the number of clusters you want to run the " + System.Environment.NewLine + "traditional k-means"); 
        }

         private void pictureBox15_MouseHover(object sender, EventArgs e)
        {
            ToolTip toolTip3 = new ToolTip();
            toolTip3.ShowAlways = true;
            toolTip3.IsBalloon = true;
            toolTip3.ToolTipTitle = "improved result";
            toolTip3.SetToolTip(pictureBox15, "the program will run the second algorithm which will calculate and find" + System.Environment.NewLine + "the correct number of clusters that suit the image by running " + System.Environment.NewLine + "our consensus algorithm on many samples from the dataset");
        }

        private void chart1_MouseHover(object sender, EventArgs e)
        {
            ToolTip toolTip4 = new ToolTip();
            toolTip4.ShowAlways = true;
            toolTip4.SetToolTip(chart1, "double click to enlarge");
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkLabel1.LinkVisited = true;
            System.Diagnostics.Process.Start("http://www.youtube.com/watch?v=J1aG6VIcsK4");
        }//first video

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkLabel2.LinkVisited = true;
            System.Diagnostics.Process.Start("http://www.youtube.com/watch?v=FUT65bzCm04&feature=relmfu");
        }//second video

        private void history_MeasureItem(object sender, MeasureItemEventArgs e)
        {
            e.ItemHeight = 150;
        }//for the list box

        private void DrawItemHandler(object sender, DrawItemEventArgs e)        
        {
            ListBox lst = sender as ListBox;
            Image planet = (Image)lst.Items[e.Index];
            //draw back groud of the item            
            e.DrawBackground();

            switch (e.Index)
            {
                case 0:
                    {
                        Image img = global::KMeansClustering.Properties.Resources.duck;
                        e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 150, 150);
                        break;
                    }
                case 1:
                    {
                        Image img = global::KMeansClustering.Properties.Resources.pig;
                        e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 150, 150);
                        break;
                    }
                case 2:
                    {
                        Image img = global::KMeansClustering.Properties.Resources.car;
                        e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 150, 150);
                        break;
                    }
                case 3:
                    {
                        Image img = global::KMeansClustering.Properties.Resources.cup;
                        e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 150, 150);
                        break;
                    }
                case 4:
                    {
                        Image img = global::KMeansClustering.Properties.Resources.star;
                        e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 150, 150);
                        break;
                    }
                case 5:
                    {
                        Image img = global::KMeansClustering.Properties.Resources.cat;
                        e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 150, 150);
                        break;
                    }
                case 6:
                    {
                        Image img = global::KMeansClustering.Properties.Resources.colorful;
                        e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 150, 150);
                        break;
                    }
                case 7:
                    {
                        Image img = global::KMeansClustering.Properties.Resources.green;
                        e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 150,150);
                        break;
                    }
                default: 
                    {
                        e.DrawFocusRectangle();   
                        break;
                    }
            }//switch
        }//listbox DrawItemHandler

        private void history_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (history.SelectedIndex == 0)//duck
            {
                pictureBox16.Image = Properties.Resources.duck2;//2
                pictureBox20.Image = Properties.Resources.duck3;//3
                pictureBox23.Image = Properties.Resources.duck4;//4
                pictureBox18.Image = Properties.Resources.duck5;//5
                pictureBox21.Image = Properties.Resources.duck6;//6
                pictureBox24.Image = Properties.Resources.duck7;//7
                pictureBox19.Image = Properties.Resources.duck8;//8
                pictureBox22.Image = Properties.Resources.duck9;//9
                label14.Text = "8280";
                label16.Text = "01:16:31:42";
                label18.Text = "5";
                historyImg = 1;
            }
            else if (history.SelectedIndex == 1)//pig
            {
                pictureBox16.Image = Properties.Resources.pig2;//2
                pictureBox20.Image = Properties.Resources.pig3;//3
                pictureBox23.Image = Properties.Resources.pig4;//4
                pictureBox18.Image = Properties.Resources.pig5;//5
                pictureBox21.Image = Properties.Resources.pig6;//6
                pictureBox24.Image = Properties.Resources.pig7;//7
                pictureBox19.Image = Properties.Resources.pig8;//8
                pictureBox22.Image = Properties.Resources.pig9;//9
                label14.Text = "7564";
                label16.Text = "01:10:28:24";
                label18.Text = "6";
                historyImg = 2;
            }
            else if (history.SelectedIndex == 2)//car
            {
                pictureBox16.Image = Properties.Resources.car2;//2
                pictureBox20.Image = Properties.Resources.car3;//3
                pictureBox23.Image = Properties.Resources.car4;//4
                pictureBox18.Image = Properties.Resources.car5;//5
                pictureBox21.Image = Properties.Resources.car6;//6
                pictureBox24.Image = Properties.Resources.car7;//7
                pictureBox19.Image = Properties.Resources.car8;//8
                pictureBox22.Image = Properties.Resources.car9;//9
                label14.Text = "7919";
                label16.Text = "01:18:53:28";
                label18.Text = "5";
                historyImg = 3;
            }
            else if (history.SelectedIndex == 3)//cup
            {
                pictureBox16.Image = Properties.Resources.cup2;//2
                pictureBox20.Image = Properties.Resources.cap3;//3
                pictureBox23.Image = Properties.Resources.cup4;//4
                pictureBox18.Image = Properties.Resources.cup5;//5
                pictureBox21.Image = Properties.Resources.cup6;//6
                pictureBox24.Image = Properties.Resources.cup7;//7
                pictureBox19.Image = Properties.Resources.cup8;//8
                pictureBox22.Image = Properties.Resources.cup9;//9
                label14.Text = "8098";
                label16.Text = "01:15:38:27";
                label18.Text = "4";
                historyImg = 4;
            }
            else if (history.SelectedIndex == 4)//star
            {
                pictureBox16.Image = Properties.Resources.star2;//2
                pictureBox20.Image = Properties.Resources.star3;//3
                pictureBox23.Image = Properties.Resources.star4;//4
                pictureBox18.Image = Properties.Resources.star5;//5
                pictureBox21.Image = Properties.Resources.star6;//6
                pictureBox24.Image = Properties.Resources.star7;//7
                pictureBox19.Image = Properties.Resources.star8;//8
                pictureBox22.Image = Properties.Resources.star9;//9
                label14.Text = "6888";
                label16.Text = "01:18:53:28";
                label18.Text = "8";
                historyImg = 5;
            }
            else if (history.SelectedIndex == 5)//cat
            {
                pictureBox16.Image = Properties.Resources.cat2;//2
                pictureBox20.Image = Properties.Resources.cat3;//3
                pictureBox23.Image = Properties.Resources.cat4;//4
                pictureBox18.Image = Properties.Resources.cat5;//5
                pictureBox21.Image = Properties.Resources.cat6;//6
                pictureBox24.Image = Properties.Resources.cat7;//7
                pictureBox19.Image = Properties.Resources.cat8;//8
                pictureBox22.Image = Properties.Resources.cat9;//9
                label14.Text = "8371";
                label16.Text = "01:12:17:29";
                label18.Text = "4";
                historyImg = 6;
            }
            else if (history.SelectedIndex == 6)//colorful
            {
                pictureBox16.Image = Properties.Resources.c2;//2
                pictureBox20.Image = Properties.Resources.c3;//3
                pictureBox23.Image = Properties.Resources.c4;//4
                pictureBox18.Image = Properties.Resources.c5;//5
                pictureBox21.Image = Properties.Resources.c6;//6
                pictureBox24.Image = Properties.Resources.c7;//7
                pictureBox19.Image = Properties.Resources.c8;//8
                pictureBox22.Image = Properties.Resources.c9;//9
                label14.Text = "10607";
                label16.Text = "01:25:05:48";
                label18.Text = "7";
                historyImg = 7;
            }
            else if (history.SelectedIndex == 7)//green
            {
                pictureBox16.Image = Properties.Resources.green2;//2
                pictureBox20.Image = Properties.Resources.green3;//3
                pictureBox23.Image = Properties.Resources.green4;//4
                pictureBox18.Image = Properties.Resources.green5;//5
                pictureBox21.Image = Properties.Resources.green6;//6
                pictureBox24.Image = Properties.Resources.green7;//7
                pictureBox19.Image = Properties.Resources.green8;//8
                pictureBox22.Image = Properties.Resources.green9;//9
                label14.Text = "4778";
                label16.Text = "00:50:04:49";
                label18.Text = "2";
                historyImg = 8;
            }
        }//history_SelectedIndexChanged

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result1=MessageBox.Show(this, "Are you sure you want to close?", "Close Application?", MessageBoxButtons.YesNo);
            if (DialogResult.Yes == result1)
            {
                this.Hide();
                e.Cancel = true; // this cancels the close event.
            }
            else if (DialogResult.No == result1)
            { e.Cancel = true; }

        }//MainForm_FormClosing

        private void pictureBox25_Click(object sender, EventArgs e)
        {
            switch (historyImg)
            {
                case 1:
                    {
                        this.historyChart = new historyChartForm(Properties.Resources.duckChart);
                        break;
                    }
                case 2:
                    {
                        this.historyChart = new historyChartForm(Properties.Resources.pigChart);
                        break;
                    }
                case 3:
                    {
                        this.historyChart = new historyChartForm(Properties.Resources.carChart);
                        break;
                    }
                case 4:
                    {
                        this.historyChart = new historyChartForm(Properties.Resources.cupChart);
                        break;
                    }
                case 5:
                    {
                        this.historyChart = new historyChartForm(Properties.Resources.starChart);
                        break;
                    }
                case 6:
                    {
                        this.historyChart = new historyChartForm(Properties.Resources.catChart);
                        break;
                    }
                case 7:
                    {
                        this.historyChart = new historyChartForm(null);
                        break;
                    }
                case 8:
                    {
                        this.historyChart = new historyChartForm(Properties.Resources.greenChart);
                        break;
                    }
            }//switch
            if (historyImg == 0) MessageBox.Show("you must choose image first", "Important Note", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else  this.historyChart.Show();
        }//pictureBox25_Click

        private void pictureBox26_MouseHover(object sender, EventArgs e)
        {
            ToolTip toolTip5 = new ToolTip();
            toolTip5.ShowAlways = true;
            toolTip5.IsBalloon = true;
            toolTip5.ToolTipTitle = "improved result chart";
            toolTip5.SetToolTip(pictureBox26, "click to see the \"imroving algorithm\" chart");
        }//MainForm_FormClosing
    }//public partial class MainForm : Form
}//namespace KMeansClustering

